<?php


namespace app\erp\controller;


use app\admin\controller\Base;
use app\admin\model\Admin as AdminModel;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthGroupAccess as AuthGroupAccessModel;
use app\common\widget\Widget;
use app\user\model\User as UserModel;
use think\Db;

class Admin extends Base
{
    /**
     * 管理员列表
     * @throws
     */
    public function index()
    {
        $search_name = input('search_name');
        $this->assign('search_name', $search_name);
        $map = [];
        $adminModel=new AdminModel;
        $ids= $adminModel->get_34ids();
        $ids=implode(',',$ids);
//        dump($ids);
        $map[] = ['id', 'in', $ids];


        if ($search_name) {
            $map[] = ['username', 'like', "%" . $search_name . "%"];
        }
        $admin_model = new AdminModel();
        $admin_list  = $admin_model->with('groups')
            ->where($map)->order('id')
            ->paginate(config('paginate.list_rows'), false, ['query' => get_query()]);
        //->select();
        // dump($admin_list);die;

        $page        = $admin_list->render();
        $page        = preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)", "<a href='javascript:ajax_page($1);'>$2</a>", $page);
        $data        = $admin_list->items();
        //表格字段
        $fields = [
            ['title' => 'ID', 'field' => 'id'],
            ['title' => '用户名', 'field' => 'username'],
//            ['title' => '邮箱', 'field' => 'email'],
            ['title' => '用户组', 'field' => 'groups.0.title'],//因为是多对多,默认只取第1个组
            ['title' => '真实姓名', 'field' => 'realname'],
//            ['title' => '登录次数', 'field' => 'logtimes'],
//            ['title' => '登录IP', 'field' => 'last_ip'],
            ['title' => '创建时间', 'field' => 'create_time', 'type' => 'datetime']
        ];
        //主键
        $pk = 'id';
        //右侧操作按钮
        $right_action = [
//            'edit'   => ['href' => url('edit'), 'is_pop' => 1],
            'delete' => url('del')
        ];
        $search       = [
            ['text', 'search_name', '', $search_name, '', '', 'text', ['placeholder' => '输入用户名', 'is_formgroup' => false], 'search-query'],
            ['button', '搜索', ['class' => 'btn btn-purple btn-sm search-query ajax-search-form2', 'type' => 'submit', 'icon_l' => 'ace-icon fa fa-search icon-on-right bigger-110']]
        ];
        $form         = [
            'href'  => url('index'),
            'class' => 'form-search',
        ];
        //实例化表单类
        $widget = new Widget();
        if (request()->isAjax()) {
            return $widget
                ->form('table', $fields, $pk, $data, $right_action, $page, '', '', 1);
        } else {
            return $widget
                ->addToparea(['add' => ['href' => url('add'), 'is_pop' => 1]], [], $search, $form)
                ->addtable($fields, $pk, $data, $right_action, $page)
                ->setButton()
                ->fetch();
        }
    }

    /**
     * 管理员添加
     */
    public function add()
    {
        if (request()->isPost()){
            $rst = AdminModel::add(input('username'), '', input('password'), input('email', ''), input('realname', ''), input('group_id', 1, 'intval'));
            if (is_int($rst) && $rst) {
                $this->success('管理员添加成功', 'index', ['is_frame' => 1]);
            } elseif (is_string($rst)) {
                $this->error($rst, 'index', ['is_frame' => 1]);
            } else {
                $this->error('管理员添加失败', 'index', ['is_frame' => 1]);
            }
        }else{
            $auth_group_model = new AuthGroupModel();
            $auth_group       = $auth_group_model->where('id','in','3,4')->column('title', 'id');
            $widget           = new Widget();
            return $widget
                ->addSelect('group_id', '所属用户组', $auth_group, '', '*', 'required', ['default' => '请选择所属组'])
                ->addText('username', '用户名', '', '*', 'required', 'text', ['placeholder' => '英文数字'])
                ->addText('password', '密码', '', '*', 'required', 'text', ['placeholder' => '输入密码'])
                ->addText('email', '邮箱', '', '', '', 'email', ['placeholder' => '输入邮箱'])
                ->addText('realname', '真实姓名', '', '', '', 'text', ['placeholder' => '真实姓名'])
                ->setUrl(url('add'))
                ->setAjax('ajaxForm-noJump')
                ->fetch();
        }

    }


 

    /**
     * 管理员删除
     */
    public function del()
    {
        $admin_id = input('id');
        if (empty($admin_id)) {
            $this->error('用户ID不存在', 'index');
        }
        if ($admin_id == session('admin_auth.aid')) {
            $this->error('不能删除自身', 'index');
        }
        if ($admin_id == 1) {
            $this->error('不能删除ID为1的管理员', 'index');
        }
        $access_model = new AuthGroupAccessModel;
        // 启动事务
        Db::startTrans();
        try {
            $admin = AdminModel::get($admin_id);
            $access_model->where('uid', $admin_id)->delete();
            AdminModel::destroy($admin_id);
            //删除对应uid
            UserModel::del($admin['uid']);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('管理员删除失败', 'index');
        }
        $this->success('管理员删除成功', 'index');
    }
}